<template>
  <div class="extra-review-submit">
    <a-card title="提交附加分申请">
      <a-form
        :model="formData"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="证书类别" required>
          <a-select 
            v-model:value="formData.sort" 
            placeholder="请选择"
            :loading="loadingCertificates"
            @change="formData.ranks = ''; formData.name = ''; formData.levels = ''"
          >
            <a-select-option v-for="sort in sortOptions" :key="sort" :value="sort">
              {{ sort }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="级别" required>
          <a-select 
            v-model:value="formData.ranks" 
            placeholder="请选择"
            :disabled="!formData.sort"
            @change="formData.name = ''; formData.levels = ''"
          >
            <a-select-option v-for="rank in ranksOptions" :key="rank" :value="rank">
              {{ rank }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="证书名称" required>
          <a-select 
            v-model:value="formData.name" 
            placeholder="请选择"
            :disabled="!formData.ranks"
            show-search
            :filter-option="(input: string, option: any) => option.children[0].children.toLowerCase().includes(input.toLowerCase())"
            @change="handleNameChange"
          >
            <a-select-option v-for="cert in nameOptions" :key="cert.id" :value="cert.name">
              {{ cert.name }} (分数：{{ cert.grade }})
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="等级" required>
          <a-select 
            v-model:value="formData.levels" 
            placeholder="请选择"
            :disabled="!formData.name"
          >
            <a-select-option v-for="cls in classesOptions" :key="cls" :value="cls">
              {{ cls }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="获奖年份" required>
          <a-date-picker v-model:value="formData.time" picker="year" style="width: 100%" />
        </a-form-item>
        
        <a-form-item label="证书图片" required>
          <a-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :max-count="1"
            :before-upload="handleBeforeUpload"
            @remove="handleRemove"
          >
            <div v-if="fileList.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">上传图片</div>
            </div>
          </a-upload>
          <div class="tip">支持jpg、png格式，大小不超过5MB</div>
        </a-form-item>
        
        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-space>
            <a-button type="primary" @click="handleSubmit">提交申请</a-button>
            <a-button @click="$router.back()">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { extraReviewAPI } from '@/api/extraReview'
import { certificateAPI } from '@/api/certificate'
import type { Certificate } from '@/api/certificate'
import { uploadToServer } from '@/utils/cosUpload'
import type { UploadProps } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'

const router = useRouter()

// 证书字典数据
const certificates = ref<Certificate[]>([])
const loadingCertificates = ref(false)

const formData = ref<{
  sort: string
  name: string
  ranks: string
  levels: string
  time: Dayjs | null
  picture: File | null
}>({
  sort: '',
  name: '',
  ranks: '',
  levels: '',
  time: null,
  picture: null
})

const fileList = ref<any[]>([])

// 加载证书字典
const loadCertificates = async () => {
  loadingCertificates.value = true
  try {
    const res = await certificateAPI.getCertificateList({ page_size: 1000 })
    certificates.value = res.data.results
  } catch (error: any) {
    message.error('加载证书字典失败')
  } finally {
    loadingCertificates.value = false
  }
}

// 获取去重后的类别列表
const sortOptions = computed(() => {
  return [...new Set(certificates.value.map(c => c.sort))]
})

// 根据选择的类别筛选级别
const ranksOptions = computed(() => {
  if (!formData.value.sort) return []
  const filtered = certificates.value.filter(c => c.sort === formData.value.sort)
  return [...new Set(filtered.map(c => c.ranks))]
})

// 根据选择的类别和级别筛选等级
const classesOptions = computed(() => {
  if (!formData.value.sort || !formData.value.ranks) return []
  const filtered = certificates.value.filter(c => 
    c.sort === formData.value.sort && c.ranks === formData.value.ranks
  )
  return [...new Set(filtered.map(c => c.classes))]
})

// 根据选择的证书名称筛选
const nameOptions = computed(() => {
  if (!formData.value.sort || !formData.value.ranks) return []
  return certificates.value.filter(c => 
    c.sort === formData.value.sort && c.ranks === formData.value.ranks
  )
})

// 当用户选择证书名称时，自动填充等级
const handleNameChange = (name: string) => {
  const cert = certificates.value.find(c => 
    c.name === name && 
    c.sort === formData.value.sort && 
    c.ranks === formData.value.ranks
  )
  if (cert) {
    formData.value.levels = cert.classes
  }
}

// 上传前处理
const handleBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isImage) {
    message.error('只能上传 JPG/PNG 格式的图片！')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB！')
    return false
  }
  formData.value.picture = file
  return false // 阻止自动上传
}

// 移除图片
const handleRemove = () => {
  formData.value.picture = null
}

const handleSubmit = async () => {
  // 验证必填项
  if (!formData.value.sort) {
    message.warning('请选择证书类别')
    return
  }
  if (!formData.value.name) {
    message.warning('请输入证书名称')
    return
  }
  if (!formData.value.ranks) {
    message.warning('请选择级别')
    return
  }
  if (!formData.value.levels) {
    message.warning('请选择等级')
    return
  }
  if (!formData.value.time) {
    message.warning('请选择获奖年份')
    return
  }
  if (!formData.value.picture) {
    message.warning('请上传证书图片')
    return
  }

  try {
    // 1. 先通过后端上传图片到COS
    message.loading({ content: '正在上传图片...', key: 'upload', duration: 0 })
    
    const uploadResult = await uploadToServer(formData.value.picture, 'zongce')
    
    if (!uploadResult.success) {
      message.error({ content: uploadResult.message, key: 'upload' })
      return
    }
    
    message.success({ content: '图片上传成功', key: 'upload' })
    
    // 2. 提交审查申请，传入COS图片URL
    const submitData = {
      sort: formData.value.sort,
      name: formData.value.name,
      ranks: formData.value.ranks,
      levels: formData.value.levels,
      time: formData.value.time.year(),
      picture: uploadResult.url  // 传COS的URL
    }

    await extraReviewAPI.submitExtraReview(submitData as any)
    message.success('提交成功，等待审核')
    router.push('/extra-review/list')
  } catch (error: any) {
    message.error(error.response?.data?.message || '提交失败')
  }
}

// 组件加载时获取证书字典
loadCertificates()
</script>

<style scoped>
.tip {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}
</style>
